﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore2.Localization;
using Microsoft.Extensions.Localization;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace Acme.BookStore2
{
    public class VehicleManager : DomainService
    {
        private readonly IVehicleRepository _vehicleRepository;
        protected IStringLocalizer<BookStore2Resource> Localizer { get; }
        
        public VehicleManager(
            IVehicleRepository vehicleRepository, 
            IStringLocalizer<BookStore2Resource> localizer)
        {
            _vehicleRepository = vehicleRepository;
            Localizer = localizer;
        }

        public async Task CreateAsync(Vehicle vehicle)
        {
            Check.NotNull(vehicle, nameof(vehicle));
            await ValidateVeichleAsync(vehicle);
            await _vehicleRepository.InsertAsync(vehicle);
        }
        
        public async Task UpdateAsync(Vehicle vehicle)
        {
            Check.NotNull(vehicle, nameof(vehicle));
            vehicle.CheckMaintenance();
            await ValidateVeichleAsync(vehicle);
            await _vehicleRepository.UpdateAsync(vehicle);
        }

        public async Task SetMaintenanceAsync(Vehicle vehicle, bool isMaintaining)
        {
            if (isMaintaining)
            {
                vehicle.StartMaintenance();
            }
            else
            {
                vehicle.EndMaintenance();
            }

            await _vehicleRepository.UpdateAsync(vehicle);
        }
        
        public async Task DeleteAsync(Vehicle vehicle)
        {
            Check.NotNull(vehicle, nameof(vehicle));
            vehicle.CheckMaintenance();
            await _vehicleRepository.DeleteAsync(vehicle);
        }
        
        protected virtual async Task ValidateVeichleAsync(Vehicle vehicle)
        {
            if (await _vehicleRepository.AnyAsync(ve => ve.Number == vehicle.Number, vehicle.Id))
            {
                throw new UserFriendlyException(Localizer["Vehicles.Vehicle.DuplicateNumberWarning", vehicle.Number]);
            }
            if (!vehicle.LicensePlateNumber.IsNullOrWhiteSpace() && await _vehicleRepository.AnyAsync(ve => ve.LicensePlateNumber == vehicle.LicensePlateNumber, vehicle.Id))
            {
                throw new UserFriendlyException(Localizer["Vehicles.Vehicle.DuplicateLicensePlateNumberWarning", vehicle.LicensePlateNumber]);
            }
        }
    }
}